﻿#if NET45 || NETSTANDARD2_0 || NET6_0
using System;
using System.Threading.Tasks;

namespace FastEmit
{
    public class ValueTaskAccessor
    {

        private readonly MethodInvoker asTaskInvoker;

        private readonly MemberGetter resultGetter;

        public ValueTaskAccessor(Type type)
        {
            asTaskInvoker = MethodExtensions.DelegateForCallMethod(type, "AsTask");
            resultGetter = PropertyExtensions.DelegateForGetPropertyValue(type, "Result");
        }

        public MethodInvoker AsTaskInvoker => asTaskInvoker;

        public MemberGetter ResultGetter => resultGetter;

        public object GetResult(object obj)
        {
            var wrap = ValueTypeExtensions.WrapIfValueType(obj);
            return resultGetter(wrap);
        }

        public async Task<object> GetResultAsync(object obj)
        {
            var wrap = ValueTypeExtensions.WrapIfValueType(obj);
            var task = (Task)AsTaskInvoker(wrap);
            await task;
            return resultGetter(wrap);
        }
    }

}
#endif
